import { useSocketStore } from "../stores/imsocket";

const socketStore = useSocketStore();

const config = {
    iceServers: [
        {
            urls: "turn:114.132.218.36:3478",
            username: "kurento",
            credential: "kurento"
        },
        {
            urls: "stun:stun.l.google.com:19302"
        },
        {
            urls: "stun:stun1.l.google.com:19302"
        },
        {
            urls: "stun:stun3.l.google.com:19302"
        },
        {
            urls: "stun:stun4.l.google.com:19302"
        }
    ],
    iceTransportPolicy: "all",
    iceCandidatePoolSize: "0"
};

/**新建RTCPeerconnection对象 */
const createPeerConn = (config: any) => {
    console.log(config);
    socketStore.peerConn = new RTCPeerConnection(config);
};

/**给RTC添加视频流 */
const bindTracks = () => {
    socketStore.stream?.getTracks().forEach((item) => {
        console.log("添加的track", item);
        socketStore.peerConn?.addTrack(item, socketStore.stream as MediaStream);
    });
};

/**创建信令信息 */
const createOffer = (option: Object, callback: Function) => {
    socketStore.peerConn?.createOffer(option).then((offer) => {
        console.log("己方offer", offer);
        socketStore.peerConn?.setLocalDescription(offer).then(() => {
            socketStore.localOffer = socketStore.peerConn?.localDescription;
            callback && callback();
        });
    });
};

/**创建应答信息 */
const createAnswer = (callback: Function) => {
    socketStore.peerConn?.createAnswer().then((answer) => {
        socketStore.peerConn?.setLocalDescription(answer).then(() => {
            socketStore.localOffer = socketStore.peerConn?.localDescription;
            callback && callback();
        });
    });
};

/**保存对端的信令信息 */
const setRemoteSdp = (offer: any) => {
    socketStore.peerConn?.setRemoteDescription(offer).then(() => {
        console.log("对方offer消息已设置！");
        socketStore.remoteOffer = offer;
    });
};

/*保存peer接收到的音视频流 */
const getRemoteStream = (callback: Function) => {
    console.log("开始监听对方媒体流");
    socketStore.peerConn?.addEventListener("track", (e: any) => {
        console.log("接受到对方的媒体流", e);
        callback(e.streams[0], e.track.kind);
    });
};

/**设置己方ice信息 */
const onIceCandidate = (candidate: any, callback: Function) => {
    try {
        const req = {
            type: "candidate",
            content: candidate
        };
        callback && callback(req);
    } catch (e) {
        console.log(e);
    }
};

/**呼叫对方 */
const call = (callback: Function, callback2: Function) => {
    // 1. 生成并发送candidate信息
    socketStore.peerConn?.addEventListener("icecandidate", (e: any) => {
        console.log("己方candidate", e);
        onIceCandidate(e.candidate, callback);
    });
    // 2. 发送信令信息
    const offerOptions = {
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 1
    };
    createOffer(offerOptions, callback2);
};

/**接收方，保存对方的sdp 和 ice */
const answer_p2 = async (
    data: { type: string; content: any },
    callback1: Function,
    callback2: Function,
    callback: Function,
    callback3: Function
) => {
    console.log("接受p1消息", data);
    switch (data.type) {
        case "offer": {
            await callback1(); // 创建peer
            await callback2(); // 开启视频流，接收远端流
            const sdp_1 = data.content;
            // 1. 保存对方发送来的sdp
            await setRemoteSdp(sdp_1);
            // 2.创建并发送应答sdp
            await createAnswer(callback);
            // 3. 生成并发送candidate信息
            socketStore.peerConn?.addEventListener("icecandidate", (e: any) => {
                console.log("己方candidate", e);
                onIceCandidate(e.candidate, callback3);
            });
            break;
        }
        case "candidate": {
            console.log("接收到对方的candidate");
            socketStore.peerConn?.addIceCandidate(data.content);
        }
    }
};

/**发送方，接收对方回应的sdp */
const answer_p1 = async (data: { type: string; content: any }) => {
    const sdp_2 = data.content;
    await setRemoteSdp(sdp_2);
};
export default {
    config,
    createPeerConn,
    bindTracks,
    createOffer,
    createAnswer,
    setRemoteSdp,
    call,
    answer_p2,
    answer_p1,
    getRemoteStream
};
